module src.database;

private import tango.text.convert.Integer;
private import tango.text.xml.Document;
private import tango.io.device.File;
private import tango.text.Util;
private import tango.io.Stdout;
private import tango.io.Path;
private import src.dbnode;

private alias char[] string;

class Database
{
  private:
    const string[] subTypes = [ "SYS", "IOS", "VC", "WW" ];
    
    DBNode[ string ][ string ] nodes;
    string[ int ] regions;
    
    string databaseVersion;
    
    void parse( Document!( char ) doc )
    {
      auto root = doc.elements;
      
      databaseVersion = doc.query[ "database" ].attribute( "v" ).nodes[ 0 ].value;
      
      foreach ( subType; subTypes )
      {
        foreach ( e; root.query[ subType ] )
        {
          string id = e.query[ "titleID" ].nodes[ 0 ].value;
          
          nodes[ subType ][ id ] = new DBNode();
          nodes[ subType ][ id ].name = e.query[ "name" ].nodes[ 0 ].value;
          nodes[ subType ][ id ].titleID = e.query[ "titleID" ].nodes[ 0 ].value;
          nodes[ subType ][ id ].ticket = ( e.query[ "ticket" ].nodes[ 0 ].value == "true" );
          
          if ( e.query[ "region" ].nodes.length > 0 )
            nodes[ subType ][ id ].region = delimit( e.query[ "region" ].nodes[ 0 ].value, "," );
          
          if ( e.query[ "version" ].nodes.length > 0 )
            nodes[ subType ][ id ].titleVersion = delimit( e.query[ "version" ].nodes[ 0 ].value, "," );
          
          if ( e.query[ "danger" ].nodes.length > 0 )
            nodes[ subType ][ id ].danger = e.query[ "danger" ].nodes[ 0 ].value;
          
          if ( e.query[ "type" ].nodes.length > 0 )
            nodes[ subType ][ id ].type = e.query[ "name" ].nodes[ 0 ].value;
        }
      }
      
      foreach ( region; root.query[ "REGIONS" ][ "region" ] )
      {
        auto index = region.attributes.name( null, "index" );
        
        if ( index )
          regions[ Integer.parse( index.value ) ] = region.value;
      }
    }
    
  public:
    this()
    {
      if ( !exists( "database.xml" ) )
        throw new Exception( "Missing database.xml" );
      
      auto doc = new Document!( char );
      doc.parse( cast( string ) File.get( "database.xml" ) );
      
      parse( doc );
    }
}